package com.wft.design.upms.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wft.design.common.core.validation.AddValidation;
import com.wft.design.common.security.annotation.PreAuthorize;
import com.wft.design.common.security.service.AuthenticationManager;
import com.wft.design.upms.entity.SysDept;
import com.wft.design.upms.entity.SysUserInfo;
import com.wft.design.upms.service.SysDeptService;
import com.wft.design.upms.service.SysUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author WFT
 * @date 2020/2/5
 * description: 用户控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/user")
public class UserController {

    private final AuthenticationManager authenticationManager;
    private final SysUserInfoService userInfoService;
    private final SysDeptService deptService;

    /**
     * 获取当前用户信息
     * @return com.wft.design.upms.entity.SysUserInfo
     */
    @PreAuthorize
    @GetMapping(value = "/getMeInfo")
    public SysUserInfo getMeInfo(){
        //  获取当前登录用户的Id
        Long accountId = this.authenticationManager.getAuthentication().getAccountId();
        return this.userInfoService.selectById(accountId);
    }

    /**
     * 分页查询用户列表
     * @param page com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysUserInfo>
     * @param params com.wft.design.upms.entity.SysUserInfo
     * @return com.baomidou.mybatisplus.core.metadata.IPage<SysUserInfo>
     */
    @GetMapping(value = "/page")
    @PreAuthorize
    public IPage<SysUserInfo> page(Page<SysUserInfo> page, SysUserInfo params){
        return this.userInfoService.pagingQuery(page,params);
    }

    /**
     * 添加用户信息
     * @param params com.wft.design.upms.entity.SysUserInfo
     */
    @PostMapping
    @PreAuthorize
    public void add(@Validated(value = AddValidation.class) @RequestBody SysUserInfo params){
        //  判断用户名是否存在
        SysUserInfo userInfo = this.userInfoService.selectByUsername(params.getUsername());
        Assert.isNull(userInfo,"用户名已存在");
        //  判断部门Id是否存在
        if (null != params.getDeptId()){
            SysDept dept = this.deptService.getById(params.getDeptId());
            Assert.notNull(dept,"部门Id不存在");
            params.setDeptName(dept.getDeptName());
        }
        this.userInfoService.create(params);
    }

    /**
     * 删除用户
     * @param userId 用户Id
     */
    @DeleteMapping(value = "{userId}")
    @PreAuthorize
    public void delete(@PathVariable(value = "userId") Long userId){
        this.userInfoService.delete(userId);
    }

}
